let selectedFile = null;
let isUploading = false;  // 添加一个标志位

// 将二维列表转换为二维数组
function listToMatrix(list) {
    return list.map(row => row.map(item => parseFloat(item)));
}

// 将二维数组转换为字符串
function matrixToString(matrix) {
    return matrix.map(row => row.join(', ')).join('<br>');
}

function formatMatrix(matrix) {
    return matrix.map(row => row.join('\t')).join('\n');
}

function sendData() {
    if (!selectedFile) {
        alert('请先选择一个文件');
        return;
    }

    if (isUploading) {
        console.log('正在上传，请稍候...');
        return;
    }

    isUploading = true;  // 设置标志位为 true

    const formData = new FormData();
    formData.append('file', selectedFile);

    const resultBox = document.getElementById('resultBox');
    
    // 检查元素是否存在
    if (!resultBox) {
        console.error('resultBox not found');
        isUploading = false;  // 重置标志位
        return;
    }



    resultBox.innerText = '';


    fetch('/upload', {  // 确保URL与Flask服务器一致
        method: 'POST',
        body: formData
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        if (data.error) {
            throw new Error(data.error);
        }


        // 显示图像
        resultBox.innerHTML = ''; // 清空之前的内容
        if (data.image_1 && data.image_1.length > 0) {
            data.image_1.forEach((imgBase64_1, index) => {
                const img_1 = document.createElement('img');
                img_1.src = 'data:image/png;base64,' + imgBase64_1;
                img_1.alt = `Sample ${index}`;
                img_1.style.display = 'block'; // 确保图像以块级元素显示
                img_1.style.margin = '10px auto'; // 确保图像居中显示
                resultBox.appendChild(img_1);
            });
        } else {
            resultBox.innerText = '没有图像数据。';
        }
        if (data.image_2 && data.image_2.length > 0) {
            data.image_2.forEach((imgBase64_2, index) => {
                const img_2 = document.createElement('img');
                img_2.src = 'data:image/png;base64,' + imgBase64_2;
                img_2.alt = `Sample ${index}`;
                img_2.style.display = 'block'; // 确保图像以块级元素显示
                img_2.style.margin = '10px auto'; // 确保图像居中显示
                resultBox.appendChild(img_2);
            });
        } else {
            resultBox.innerText = '没有图像数据。';
        }
    })
    .catch(error => {
        resultBox.innerText = '处理失败，请重试。';
        console.error('There was a problem with the fetch operation:', error);
    })
    .finally(() => {
        isUploading = false;  // 重置标志位
    });
}



function handleFileSelect(event) {
    selectedFile = event.target.files[0];
    if (selectedFile && selectedFile.name.endsWith('.mat')) {
        document.getElementById('fileDropZone').innerText = selectedFile.name;
        document.getElementById('submitButton').disabled = false; // 启用提交按钮
        sendData();  // 选择文件后立即发送数据
    } else {
        alert('请上传一个 .mat 文件');
        selectedFile = null;
        document.getElementById('fileDropZone').innerText = '选择文件或拖拽文件到这里';
        document.getElementById('submitButton').disabled = true; // 禁用提交按钮
    }
}

function handleDrop(event) {
    event.preventDefault();
    selectedFile = event.dataTransfer.files[0];
    if (selectedFile && selectedFile.name.endsWith('.mat')) {
        document.getElementById('fileDropZone').innerText = selectedFile.name;
        document.getElementById('submitButton').disabled = false; // 启用提交按钮
        sendData();  // 拖拽文件后立即发送数据
    } else {
        alert('请上传一个 .mat 文件');
        selectedFile = null;
        document.getElementById('fileDropZone').innerText = '选择文件或拖拽文件到这里';
        document.getElementById('submitButton').disabled = true; // 禁用提交按钮
    }
}

function handleDragOver(event) {
    event.preventDefault();
}

function handleClick() {
    document.getElementById('fileInput').click();
}

function handleCancel() {
    selectedFile = null;
    document.getElementById('fileInput').value = '';
    document.getElementById('fileDropZone').innerText = '选择文件或拖拽文件到这里';
    document.getElementById('resultBox').innerHTML = '';
    document.getElementById('finalResultBox').innerHTML = ''; // 清空新增的输出框内容
    document.getElementById('submitButton').disabled = true; // 禁用提交按钮
}

function handleSubmit() {
    if (!selectedFile) {
        alert('请先选择一个文件');
        return;
    }

    const formData = new FormData();
    formData.append('file', selectedFile);

    const finalResultBox = document.getElementById('finalResultBox');
    
    // 检查元素是否存在
    if (!finalResultBox) {
        console.error('finalResultBox not found');
        return;
    }

    finalResultBox.innerText = '';

    fetch('/predict', {  // 假设新的后端程序的URL为 /predict
        method: 'POST',
        body: formData
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        if (data.error) {
            throw new Error(data.error);
        }

        //显示处理后的数组
        // finalResultBox.innerHTML = 'accuracy: ' + data.accuracy; 
        // 显示处理后的数组
        // finalResultBox.innerHTML = `<pre>${JSON.stringify(data.result, null, 0)}</pre>`;

        // 更新 finalResultBox 的内容
        finalResultBox.innerHTML = `accuracy: ${data.accuracy}<br><br>输入信号的状态:<br>${formatMatrix(listToMatrix(data.label))}<br><br>模型的预判输出:<br>${formatMatrix(listToMatrix(data.output))}`;
    })
    .catch(error => {
        finalResultBox.innerText = '处理失败，请重试。';
        console.error('There was a problem with the fetch operation:', error);
    });
}

// 定义 preventDefaultDrag 函数
function preventDefaultDrag(event) {
    event.preventDefault();
}

window.onload = function() {
    document.getElementById('fileInput').addEventListener('change', handleFileSelect);
    document.getElementById('fileDropZone').addEventListener('drop', handleDrop);
    document.getElementById('fileDropZone').addEventListener('dragover', handleDragOver);
    document.getElementById('submitButton').addEventListener('click', handleSubmit);
    document.getElementById('cancelButton').addEventListener('click', handleCancel);

    // 阻止页面中除文件选择和拖拽框以外的所有
    document.addEventListener('dragover', preventDefaultDrag);
    document.addEventListener('drop', preventDefaultDrag);
};

document.addEventListener('DOMContentLoaded', function() {
    const submitButton = document.getElementById('submitButton');

    // 添加初始的动画类
    submitButton.classList.add('animate-before');

    // 添加点击事件监听器
    submitButton.addEventListener('click', function() {
        // 移除触发动画的类
        submitButton.classList.remove('animate-before');
    });
});